<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
              <a-select v-model="model.brand" placeholder="请选择品牌">
                <a-select-option v-for="(item,index) in brandList" :key="item.id">{{ item.formulaName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="FC No" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fcNo">
              <a-select v-model="model.fcNo" placeholder="请选择FC No">
                <a-select-option v-for="(item,index) in brandList" :key="item.id">{{ item.fcNo }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="配料罐重" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ingredientTankWeight">
              <a-input v-model="model.ingredientTankWeight" placeholder="请输入配料罐重" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="料浆因子" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="slurryFactor">
              <a-input v-model="model.slurryFactor" placeholder="请输入料浆因子"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="FC.Solid" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fcSolid">
              <a-input v-model="model.fcSolid" placeholder="请输入FC.Solid" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="Crutcher CMM" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="crutcherCmm">
              <a-input v-model="model.crutcherCmm" placeholder="请输入Crutcher CMM" disabled ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class='add-box'>
          <a-button type="link" icon="plus" @click='addCavity'>添加预称重</a-button>
        </div>
        <div v-if="model.enePreWeighings.length > 0" >
          <div class='cavity-box' v-for='(item,index) in model.enePreWeighings' :key="index" v-if='model.enePreWeighings.length>0'>
            <div class='title-box'>
              <span>预称重{{ alphabetizedItems[index].letter }}</span>
              <a-popconfirm title="确定删除吗?" @confirm="() => deleteCavity(index)">
                <a-button type="link" icon="minus">删除预称重</a-button>
              </a-popconfirm>
            </div>
            <a-row>
              <a-col :span="24">
                <a-form-model-item :labelCol="labelCol3" :wrapperCol="wrapperCol3" :prop="'enePreWeighings[' + index + '].enePreWeighingMaterials'">
                  <a-row>
                    <a-col :span="24">
                      <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol3">
                        <div class='mark-infos'>
                          <a-table
                            ref="markTable"
                            size="middle"
                            :scroll="{x:false,y:false}"
                            bordered
                            :rowKey="(record = () => record.id)"
                            :columns="columns"
                            :dataSource="item.enePreWeighingMaterials"
                            :pagination="false"
                            :loading="loading"
                            class="j-table-force-nowrap1">
                            <template v-for="col in ['materialCode','material','crutcherFc','solids','water','plannedDosing','totalWater']" :slot="col" slot-scope="text, record, indx">
                              <div :key="record.id">
                                <a-form-model-item :prop="'enePreWeighings[' + index + '].enePreWeighingMaterials['+indx+'].materialCode'" v-if="col==='materialCode'">
                                  <a-input v-model="record.materialCode" disabled/>
                                </a-form-model-item>
                                <a-form-model-item :prop="'enePreWeighings[' + index + '].enePreWeighingMaterials['+indx+'].material'" v-else-if="col==='material'">
                                  <j-search-select-tag
                                    placeholder="请选择材料"
                                    type="list"
                                    v-model="record.material"
                                    dict="ene_ingredient_management,material_description,id"
                                    @change="handleMaterialChange(record)"
                                  />
                                </a-form-model-item>
                                <a-form-model-item :prop="'enePreWeighings[' + index + '].enePreWeighingMaterials['+indx+'].crutcherFc'" v-else-if="col==='crutcherFc'">
                                  <a-input placeholder='请输入Crutcher FC.' v-model="record.crutcherFc" @input="onCellChange(record)" />
                                </a-form-model-item>
                                <a-form-model-item :prop="'enePreWeighings[' + index + '].enePreWeighingMaterials['+indx+'].solids'" v-else-if="col==='solids'">
                                  <a-input v-model="record.solids" disabled/>
                                </a-form-model-item>
                                <a-form-model-item :prop="'enePreWeighings[' + index + '].enePreWeighingMaterials['+indx+'].water'" v-else-if="col==='water'">
                                  <a-input v-model="record.water" disabled/>
                                </a-form-model-item>
                                <a-form-model-item :prop="'enePreWeighings[' + index + '].enePreWeighingMaterials['+indx+'].plannedDosing'" v-else-if="col==='plannedDosing'">
                                  <a-input v-model="record.plannedDosing" disabled/>
                                </a-form-model-item>
                                <a-form-model-item :prop="'enePreWeighings[' + index + '].enePreWeighingMaterials['+indx+'].totalWater'" v-else-if="col==='totalWater'">
                                  <a-input v-model="record.totalWater" disabled/>
                                </a-form-model-item>
                              </div>
                            </template>
                          </a-table>
                        </div>
                      </a-form-model-item>
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <a-table
          ref="testTable"
          size="middle"
          :scroll="{x:false,y:false}"
          bordered
          :rowKey="id"
          :columns="totalColumns"
          :dataSource="testList"
          :pagination="false"
          :loading="loading"
          class="j-table-force-nowrap1">
        </a-table>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction, postAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
import EditableCell2 from '@comp/table/EditableCell2.vue'

  export default {
    name: 'EneFormulaPgFrontForm',
    components: {
      EditableCell2
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          ingredientTankWeight:0,
          fcSolid:0,
          crutcherCmm:0,
          enePreWeighings: [
            {
              enePreWeighingMaterials: [
                {
                  id:'',
                  materialCode:'',
                  material:'',
                  crutcherFc:'',
                  solids:'',
                  water:'',
                  plannedDosing:'',
                  totalWater:'',
                },
                {
                  id:'',
                  materialCode:'',
                  material:'',
                  crutcherFc:'',
                  solids:'',
                  water:'',
                  plannedDosing:'',
                  totalWater:'',
                },
                {
                  id:'',
                  materialCode:'',
                  material:'',
                  crutcherFc:'',
                  solids:'',
                  water:'',
                  plannedDosing:'',
                  totalWater:'',
                },
                {
                  id:'',
                  materialCode:'',
                  material:'',
                  crutcherFc:'',
                  solids:'',
                  water:'',
                  plannedDosing:'',
                  totalWater:'',
                },
              ]
            }
          ]
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol1: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol1: {
          xs: { span: 24 },
          sm: { span: 21 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 17 },
        },
        labelCol3: {
          xs: { span: 24 },
          sm: { span: 3},
        },
        wrapperCol3: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
        },
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '材料代码',
            align: "center",
            dataIndex: 'materialCode',
            scopedSlots: { customRender: 'materialCode' }
          },
          {
            title:'材料',
            align:"center",
            dataIndex: 'material',
            width:180,
            scopedSlots: { customRender: 'material' }
          },
          {
            title:'Crutcher FC.',
            align:"center",
            dataIndex: 'crutcherFc',
            scopedSlots: { customRender: 'crutcherFc' }
          },
          {
            title:'Solids',
            align:"center",
            dataIndex: 'solids',
            scopedSlots: { customRender: 'solids' }
          },
          {
            title:'Water',
            align:"center",
            dataIndex: 'water',
            scopedSlots: { customRender: 'water' }
          },
          {
            title:'Planned Dosing',
            align:"center",
            dataIndex: 'plannedDosing',
            scopedSlots: { customRender: 'plannedDosing' }
          },
          {
            title:'Total Water',
            align:"center",
            dataIndex: 'totalWater',
            scopedSlots: { customRender: 'totalWater' }
          },
        ],
        totalColumns: [
          {
            title: '序号',
            align: "center",
            width:60,
            dataIndex: 'id',
          },
          {
            title: '材料代码',
            align: "center",
            width:198,
            dataIndex: 'materialCode',
          },
          {
            title:'材料',
            align:"center",
            dataIndex: 'material',
            width:180,
          },
          {
            title:'Crutcher FC.',
            align:"center",
            width:198,
            dataIndex: 'crutcherFc',
          },
          {
            title:'Solids',
            align:"center",
            width:198,
            dataIndex: 'solids',
          },
          {
            title:'Water',
            align:"center",
            width:198,
            dataIndex: 'water',
          },
          {
            title:'Planned Dosing',
            align:"center",
            width:198,
            dataIndex: 'plannedDosing',
          },
          {
            title:'Total Water',
            align:"center",
            width:198,
            dataIndex: 'totalWater',
          },
        ],
        loading: false,
        testList:[],
        brandList:[],// 品牌
        url: {
          brandList:'/craft/eneFormulaPgBase/list',
          add: "/craft/eneFormulaPgFront/add",
          edit: "/craft/eneFormulaPgFront/edit",
          queryById: "/craft/eneFormulaPgFront/queryById"
        }
      }
    },
    mounted() {
      this.getBrandList();
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      alphabetizedItems() {
        const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        return this.model.enePreWeighings.map((item, index) => ({
          letter: letters[index % letters.length], // 循环使用字母
          originalIndex: index, // 保留原始索引用于删除操作
          item // 也可以直接包含item对象，或者根据需要处理
        }));
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      // 获取品牌列表
      getBrandList(){
        getAction(this.url.brandList,{ pageSize: 100 }).then((res) => {
          if(res.success){
            this.brandList = res.result.records;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      handleMaterialChange(record){
        if (record.material === '1876870084209078273') {
          postAction('/craft/eneFormulaPgFront/compute/test', this.model).then(
            (res) => {
              if (res.success) {
                this.testList = []
                res.result.forEach(item => {
                  if (item.id === 'gongyishui'){
                    this.$set(record, 'crutcherFc', item.crutcherFc);
                    this.$set(record, 'water', item.water);
                    this.$set(record, 'solids', item.solids);
                    this.$set(record, 'plannedDosing', item.plannedDosing);
                    this.$set(record, 'totalWater', item.totalWater);
                  }else {
                    this.testList.push({
                      id: item.id,
                      material: item.id,
                      crutcherFc: item.crutcherFc,
                      solids: item.solids,
                      water: item.water,
                      plannedDosing: item.plannedDosing,
                      totalWater: item.totalWater,
                    });
                  }
                  if(item.id === 'total'){
                    this.$set(this.model, 'fcSolid', item.solids);
                    this.$set(this.model, 'ingredientTankWeight',item.plannedDosing);
                    const calculatedValue = (1 - (item.solids / item.crutcherFc)) * 100;
                    let roundedValue = calculatedValue.toFixed(2);
                    if (isNaN(roundedValue)){
                      roundedValue = 0;
                    }
                    this.$set(this.model, 'crutcherCmm', roundedValue);
                  }
                })
              }
            }
          )
        }
      },
      onCellChange(record) {
        if (record) {
          postAction('/craft/eneFormulaPgFront/compute/formula', { slurryFactor: this.model.slurryFactor, detail: record , brand: this.model.brand} ).then(
            (res) => {
              if (res.success) {
                this.$set(record, 'water', res.result.water);
                this.$set(record, 'solids', res.result.solids);
                this.$set(record, 'plannedDosing', res.result.plannedDosing);
                this.$set(record, 'totalWater', res.result.totalWater);
                if(res.result === null){
                  alert('未选择材料');
                }
                postAction('/craft/eneFormulaPgFront/compute/test', this.model).then(
                  (res) => {
                    if (res.success) {
                      this.testList = []
                      res.result.forEach(item => {
                        if (item.id !== 'gongyishui'){
                          this.testList.push({
                            id: item.id,
                            material: item.id,
                            crutcherFc: item.crutcherFc,
                            solids: item.solids,
                            water: item.water,
                            plannedDosing: item.plannedDosing,
                            totalWater: item.totalWater,
                          });
                        }
                        if(item.id === 'total'){
                          this.$set(this.model, 'fcSolid', item.solids);
                          this.$set(this.model, 'ingredientTankWeight',item.plannedDosing);
                          const calculatedValue = (1 - (item.solids / item.crutcherFc)) * 100;
                          let roundedValue = calculatedValue.toFixed(2);
                          if (isNaN(roundedValue)){
                            roundedValue = 0;
                          }
                          this.$set(this.model, 'crutcherCmm', roundedValue);
                        }
                      })
                    }
                  }
                )
              }
            }
          )
        }
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        if(record===undefined){
          this.model = {
            enePreWeighings:[
              {
                enePreWeighingMaterials:[
                  {
                    id:'',
                    materialCode:'',
                    material:'',
                    crutcherFc:'',
                    solids:'',
                    water:'',
                    plannedDosing:'',
                    totalWater:''
                  },
                  {
                    id:'',
                    materialCode:'',
                    material:'',
                    crutcherFc:'',
                    solids:'',
                    water:'',
                    plannedDosing:'',
                    totalWater:''
                  },
                  {
                    id:'',
                    materialCode:'',
                    material:'',
                    crutcherFc:'',
                    solids:'',
                    water:'',
                    plannedDosing:'',
                    totalWater:''
                  },
                  {
                    id:'',
                    materialCode:'',
                    material:'',
                    crutcherFc:'',
                    solids:'',
                    water:'',
                    plannedDosing:'',
                    totalWater:''
                  },
                ]
              }
            ]
          };
        }else{
          this.model = Object.assign({}, record);
        }
        //备份model原始值
        this.modelDefault = JSON.parse(JSON.stringify(this.model));
        if(this.disabled){
          this.isEdit = false;
        }else{
          this.isEdit = true;
        }
        this.visible = true;

        postAction('/craft/eneFormulaPgFront/compute/test', this.model).then(
          (res) => {
            if (res.success) {
              res.result.forEach(item => {
                if (item.id !== 'gongyishui'){
                  this.testList.push({
                    id: item.id,
                    material: item.id,
                    crutcherFc: item.crutcherFc,
                    solids: item.solids,
                    water: item.water,
                    plannedDosing: item.plannedDosing,
                    totalWater: item.totalWater,
                  });
                }
                if(item.id === 'total'){
                  this.$set(this.model, 'fcSolid', item.solids);
                  this.$set(this.model, 'ingredientTankWeight',item.plannedDosing);
                  const calculatedValue = (1 - (item.solids / item.crutcherFc)) * 100;
                  let roundedValue = calculatedValue.toFixed(2);
                  if (isNaN(roundedValue)){
                    roundedValue = 0;
                  }
                  this.$set(this.model, 'crutcherCmm', roundedValue);
                }
              })
            }
          }
        )
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      addCavity(){
        if(!this.model.enePreWeighings){
          this.$set(this.model,'enePreWeighings',[])
        }
        this.model.enePreWeighings.push({
          enePreWeighingMaterials:[
            {
              id:'',
              materialCode:'',
              material:'',
              crutcherFc:'',
              solids:'',
              water:'',
              plannedDosing:'',
              totalWater:''
            },
            {
              id:'',
              materialCode:'',
              material:'',
              crutcherFc:'',
              solids:'',
              water:'',
              plannedDosing:'',
              totalWater:''
            },
            {
              id:'',
              materialCode:'',
              material:'',
              crutcherFc:'',
              solids:'',
              water:'',
              plannedDosing:'',
              totalWater:''
            },
            {
              id:'',
              materialCode:'',
              material:'',
              crutcherFc:'',
              solids:'',
              water:'',
              plannedDosing:'',
              totalWater:''
            },
          ]
        });
      },
      deleteCavity(originalIndex){
        let len = this.model.enePreWeighings.length;
        if(len>1){
          this.model.enePreWeighings.splice(originalIndex,1);
        }else{
          this.$message.error("最少保留一个预称重！")
        }
      },
    },
    destroyed() {
      clearTimeout(this.timer);
      this.timer = null;
    },
  }
</script>
<style lang="scss" scoped>
.title{
  font-size: 24px;
  font-weight: bold;
}
.unit{
  padding-left: 4px;
  line-height: 40px;
}
.query-group-cust{
  width: 100%!important;
}
.ant-input-number{
  width: 100%!important;
}
.cavity-box{
  .title-box{
    height: 40px;
    padding: 0 5px;
    line-height: 40px;
    span{
      font-size: 24px;
      font-weight: bold;
      float: left;
    }
    .ant-btn-link{
      float: right;
    }
  }
  .mark-infos{
    position: relative;
    .editable-add-btn{
      position: absolute;
      top: 10px;
      right: 18px;
      z-index: 202;
    }
  }
}
</style>